package com.molyfun.parents.activity.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.MainActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.StringUtils;
import com.molyfun.parents.view.SMSCountDownTimer;
import com.molyfun.parents.view.SinglineClearEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.smssdk.SMSSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by liuchao on 7/12/16.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener{

    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.base_title_left)
    ImageView mTitleLeft;
    @InjectView(R.id.get_code)
    TextView mGetCode;

    @InjectView(R.id.register_step_one_phone_num)
    SinglineClearEditText mPhoneNum;
    @InjectView(R.id.code)
    SinglineClearEditText mCode;
    @InjectView(R.id.register_step_two_user_name)
    SinglineClearEditText mUserName;
    @InjectView(R.id.register_step_two_pwd)
    SinglineClearEditText mPwd;
    @InjectView(R.id.register_btn)
    TextView mRegisterBtn;

    SMSCountDownTimer smsCountDownTimer;

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, RegisterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.inject(this);

        getSupportActionBar().setTitle("");
        mTitle.setText("欢迎注册账号");

        mTitleLeft.setOnClickListener(this);
        mGetCode.setOnClickListener(this);
        smsCountDownTimer = new SMSCountDownTimer(mGetCode, 60000, 1000);
        mRegisterBtn.setOnClickListener(this);
        mPwd.setHint("请设置至少六位密码");
        mPhoneNum.setHint("请输入您的手机号码");
        mUserName.setHint("请输入您的用户名");
        mCode.setHint("请输入您的验证码");

        mPwd.setIsPwd();

    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.base_title_left:
                Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
                RegisterActivity.this.startActivity(loginIntent);
                break;
            case R.id.get_code:
                getSmsCode();
                break;
            case R.id.register_btn:
                if(TextUtils.isEmpty(mPhoneNum.getString())){
                    toast("手机号不能为空");
                    return;
                }
                if(!StringUtils.checkPhoneNumber(mPhoneNum.getString().trim())){
                    toast("手机号不正确");
                    return;
                }
                if(TextUtils.isEmpty(mCode.getString())){
                    toast("请输入短信验证码");
                    return;
                }
                if(TextUtils.isEmpty(mUserName.getString())){
                    toast("请输入用户名");
                    return;
                }
                if(TextUtils.isEmpty(mPwd.getString())){
                    toast("请输入密码");
                    return;
                }
                register(mPhoneNum.getString().trim(), mCode.getString().trim(), mPwd.getString().trim(), mUserName.getString().trim());
                break;
        }
    }

    private void getSmsCode(){
        if(TextUtils.isEmpty(mPhoneNum.getString())){
            toast("手机号不能为空");
            return;
        }
        if(!StringUtils.checkPhoneNumber(mPhoneNum.getString().trim())){
            toast("手机号不正确");
            return;
        }
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().getSmsCode(mPhoneNum.getString().trim(), "reg");
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if(response.body() != null){
                    if(response.body().getCode() == 200){
                        smsCountDownTimer.start();
                    }else {
                        toast(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                toast("请求失败");
            }
        });
    }

    private void register(final String phone,final String captchacode,final String pwd, final String userName){
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().register(phone,captchacode, pwd, userName);
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if(response.body() != null){
                    if(response.body().getCode() == 200){
//                        toast("注册成功，请登录");
//                        LoginActivity.startActivity(RegisterActivity.this);

                        MFPApplication.getInstance().setUser(response.body().getData());
                        if(response.body().getData() != null){

                            PreferencesStorageUtil.setToken(RegisterActivity.this, response.body().getData().getToken());
                            PreferencesStorageUtil.setUserBean(RegisterActivity.this, GsonUtil.toJson(response.body().getData()));
                            if(TextUtils.isEmpty(response.body().getData().getStudentid())){
                                PreferencesStorageUtil.setUserEnter(RegisterActivity.this, false);
                            }else{
                                PreferencesStorageUtil.setUserEnter(RegisterActivity.this, true);
                            }
                            MFPApplication.getInstance().refreshRestClient(response.body().getData().getToken());

                            PreferencesStorageUtil.setIMUserName(RegisterActivity.this, response.body().getData().getImusername());
                            PreferencesStorageUtil.setIMUserPwd(RegisterActivity.this, response.body().getData().getImpassword());
                            PreferencesStorageUtil.setStudentId(RegisterActivity.this, response.body().getData().getStudentid());
                            PreferencesStorageUtil.setPhoneNum(RegisterActivity.this, response.body().getData().getPhone());
                            PreferencesStorageUtil.setAddress(RegisterActivity.this, response.body().getData().getAddress());
                            PreferencesStorageUtil.setEmail(RegisterActivity.this, response.body().getData().getEmail());
                            PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());

                            Intent toMainIntent = new Intent(RegisterActivity.this, MainActivity.class);
                            RegisterActivity.this.startActivity(toMainIntent);
                            finish();
                        }

                    }else{
                        toast(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
//                retrofitError.getCause();
                toast("注册失败");
            }
        });
    }

    private void registerWithEncrypt( final String phone,final String pwd, final String userName, final String invitecode, final String imgurl){
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().registerWithEncrypt(phone, pwd, userName, invitecode, imgurl);
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if(response.body() != null){

                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {

            }
        });
    }

}
